import Vue from "vue";
import Vuex from "vuex";
import { getInfo, logout } from "@/api/modules/user";
import { getToken, removeToken } from "@/utils/auth";
Vue.use(Vuex);

export default new Vuex.Store({
	state: {
		tree: [],
		tabs: [],
		tabOne: [],
		title: "",
		userInfo: {
			admin: 0, //0未授权 1已授权
			user: {
				id: "844424930131969",
				name: "扶风",
				fullName: "陕西斯瑞扶风先进铜合金有限公司",
				roles: "1",
				companyId: "28428972647776257",
			},
		},
		oldUserInfo: {
			id: "844424930131969",
			name: "扶风",
			fullName: "陕西斯瑞扶风先进铜合金有限公司",
			roles: "1",
			companyId: "56857945295552513",
		},
		token: getToken(),
		isCollapse: false,
	},
	getters: {},
	mutations: {
		CHANGE_NAV_FOLD(state, value) {
			state.isCollapse = value;
		},
		SET_USERINFO(state, info) {
			state.userInfo = info;
		},
		SET_TOKEN: (state, token) => {
			state.token = token;
		},
		setRoutes(state, routes) {
			state.tree = routes;
		},
		tab(state, payload) {
			function recursion(t) {
				state.tabs.push(t);
				if (t.children && t.children.length > 0) {
					for (let i = 0; i < t.children.length; i++) {
						recursion(t.children[i]);
					}
				}
			}
			state.tree.forEach((item) => {
				recursion(item);
			});
			state.tabs.forEach((item) => {
				if (item.path === payload) {
					const ind = state.tabOne.findIndex((i) => i.path === item.path);
					state.title = item.path;
					if (ind === -1) {
						state.tabOne.push(item);
					}
				}
			});
		},
		SET_ACTIVE_TAB(state, newValue) {
			state.title = newValue;
		},
		remove(state, payload) {
			const i = state.tabOne.findIndex((item) => item.path === payload);
			if (payload !== state.title) {
				console.log(payload);
			} else if (state.tabOne.length === 1) {
				state.title = "";
			} else if (i === state.tabOne.length - 1) {
				state.title = state.tabOne[i - 1].path;
			} else {
				state.title = state.tabOne[i + 1].path;
			}
			state.tabOne.splice(i, 1);
		},
	},
	actions: {
		loadRoutes({ commit }, routes) {
			commit("setRoutes", routes);
		},
		// 获取用户信息
		GetInfo({ commit, state }) {
			return new Promise((resolve, reject) => {
				getInfo()
					.then((res) => {
						if (res.code === 200) {
							commit("SET_USERINFO", res.data);
							resolve(res);
						} else {
							reject(error);
						}
					})
					.catch((error) => {
						reject(error);
					});
			});
		},
		// 退出系统
		LogOut({ commit, state }) {
			return new Promise((resolve, reject) => {
				logout(state.token)
					.then(() => {
						commit("SET_TOKEN", "");
						removeToken();
						resolve();
					})
					.catch((error) => {
						reject(error);
					});
			});
		},
		changeNavFold({ commit }, value) {
			commit("CHANGE_NAV_FOLD", value);
		},
	},
	modules: {},
});
